/**
 * @file    代理
 * @author  zhangxueqiong@baidu.com
 */
const http = require('http');
const https = require('https');
const httpProxy = require('http-proxy');
const chalk = require('chalk');
const {
  // proxyToEnum,
  proxyModeEnum,
  proxyTo,
  proxyMode,
  pathList,
  proxyToTestPort,
} = require('./proxy.config.js');

const proxyToConfig = {
  /**
   * 测试环境
   */
  TEST: {
    proxyUrl: `http://latest.lpas.com:${proxyToTestPort}`,
    proxyHost: 'latest.lpas.com',
    devHost: 'dev.latest.lpas.com',
    agent: http.globalAgent,
  },
  /**
   * 预上线环境
   */
  PREONLINE: {
    proxyUrl: 'http://la.lpas.com',
    proxyHost: 'la.lpas.com',
    devHost: 'dev.la.lpas.com',
    agent: http.globalAgent,
  },
  /**
   * 线上环境
   */
  ONLINE: {
    proxyUrl: 'https://la.lpas.com',
    proxyHost: 'la.lpas.com',
    devHost: 'dev.la.lpas.com',
    agent: https.globalAgent,
  },
};

const isInPathList = (path) =>
  pathList.some((rule) => {
    return rule instanceof RegExp ? rule.test(path) : rule === path;
  });

const isProxyRemote = (path) =>
  proxyMode === proxyModeEnum.WHOLE ||
  (proxyMode === proxyModeEnum.WHITELIST && isInPathList(path)) ||
  (proxyMode === proxyModeEnum.BLACKLIST && !isInPathList(path));

const { proxyUrl, devHost, agent, proxyHost } = proxyToConfig[proxyTo.key];
const proxyServer = httpProxy.createProxyServer({
  target: proxyUrl,
  changeOrigin: true,
  agent,
  headers: {
    host: proxyHost,
    origin: proxyUrl,
    // referer暂时写成固定的，需要调整
    referer: `${proxyUrl}/fc`,
  },
});

proxyServer.on('error', (e) => {
  // eslint-disable-next-line no-console
  console.log(chalk.red('[proxy error, error]'), e);
});

module.exports = {
  isProxyRemote,
  proxyServer,
  host: devHost,
};
